package com.crm.dashboard.controller;

import com.crm.custinfo.controller.CustInfoController;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.custinfo.service.impl.UserInfoComm;
import com.crm.dashboard.service.IIndexDashboardService;
import com.crm.report.domain.CustVisitRecord;
import com.crm.report.service.ICustVisitRecordService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 首页大数据统计
 */
@RestController
@RequestMapping("/crmsys/indexDashboard")
public class IndexDashboardController {
    private static final Logger log = LoggerFactory.getLogger(CustInfoController.class);
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private UserInfoComm userInfoComm;
    @Autowired
    private IIndexDashboardService indexDashboardService;

    @Autowired
    private ISysDeptService isysDeptService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ICustVisitRecordService iCustVisitRecordService;

    /**
     * 获取首页的头部数据
     *
     * @return
     */
    @GetMapping("/getPanelCount")
    public AjaxResult getPanelCount() {
        int totalCust = 0, visitCust = 0, remarkCust = 0, threeCust = 0, fourCust = 0, fiveCust = 0;
        Map<String, Object> resMap = null;
        Map<String, Object> roleMap = null;
        try {
            resMap = new HashMap<String, Object>();
            CustInfo custInfo = new CustInfo();
            // 当前用户
            SysUser user = getLoginUser().getUser();
            //获取登录账号的角色信息
            roleMap = userInfoComm.getUserRoleCode();
            if (roleMap.get("is_emp").equals("1")) {
                //如果是业务员只查询自己的数据
                custInfo.setOldUserId(user.getUserId());
            } else {
                List<SysDept> sysDepts = isysDeptService.selectChildrenAllDeptById(user.getDeptId());
                Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(sysDepts);
                Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
                if (deptIds.length > 0) {
                    custInfo.setDeptIds(deptIds);
                }
            }
            String dateNow = DateUtils.getDate();
            Map<String, Object> inParams = new HashMap<String, Object>();
            inParams.put("beginoldDistributeTime", dateNow + " 00:00:00");
            inParams.put("endoldDistributeTime", dateNow + " 23:59:59");
            custInfo.setParams(inParams);

            List<CustInfo> custInfos = custInfoService.selectCustInfoList(custInfo);
            totalCust = custInfos.size();
            for (CustInfo info : custInfos) {
                CustVisitRecord custVisitRecord = new CustVisitRecord();
                custVisitRecord.setCustId(info.getId());
                if (!iCustVisitRecordService.selectCustVisitRecordList(custVisitRecord).isEmpty()) {
                    visitCust += 1;
                }
                if (info.getRemark() != null && !"".equals(info.getRemark())) {
                    remarkCust += 1;
                }
                if (info.getStarLevel() != null && "3".equals(info.getStarLevel())) {
                    threeCust += 1;
                }
                if (info.getStarLevel() != null && "4".equals(info.getStarLevel())) {
                    fourCust += 1;
                }
                if (info.getStarLevel() != null && "5".equals(info.getStarLevel())) {
                    fiveCust += 1;
                }
            }
        } catch (Exception e) {
            log.error("getPanelCount获取数据失败", e);
        }

        resMap.put("isEmp", roleMap.get("is_emp"));
        resMap.put("totalCust", totalCust);
        resMap.put("visitCust", visitCust);
        resMap.put("remarkCust", remarkCust);
        resMap.put("threeCust", threeCust);
        resMap.put("fourCust", fourCust);
        resMap.put("fiveCust", fiveCust);


        return AjaxResult.success(resMap);
    }

    /**
     * 获取首页的近七天客户数
     *
     * @return
     */
    @GetMapping("/getSevenDaysCust")
    public AjaxResult getSevenDaysCust() {
        Map<String, Object> resMap = null;
        Map<String, Object> roleMap = null;

        List<String> sevenDays = getSevenDays();
        List<Integer> sevenDaysTotal = new ArrayList<>();
        List<Integer> sevenDaysOther = new ArrayList<>();

        try {
            resMap = new HashMap<String, Object>();
            CustInfo custInfo = new CustInfo();
            // 当前用户
            SysUser user = getLoginUser().getUser();
            //获取登录账号的角色信息
            roleMap = userInfoComm.getUserRoleCode();
            if (roleMap.get("is_emp").equals("1")) {
                //如果是业务员只查询自己的数据
                custInfo.setOldUserId(user.getUserId());
            } else {
                List<SysDept> sysDepts = isysDeptService.selectChildrenAllDeptById(user.getDeptId());
                Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(sysDepts);
                Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
                if (deptIds.length > 0) {
                    custInfo.setDeptIds(deptIds);
                }
            }

            for (String sevenDay : sevenDays) {
                Map<String, Object> inParams = new HashMap<String, Object>();
                inParams.put("beginoldDistributeTime", sevenDay + " 00:00:00");
                inParams.put("endoldDistributeTime", sevenDay + " 23:59:59");
                custInfo.setParams(inParams);
                List<CustInfo> custInfos = custInfoService.selectCustInfoList(custInfo);
                int count = 0;
                sevenDaysTotal.add(custInfos.size());
                for (CustInfo info : custInfos) {
                    if (info.getStarLevel() != null && ("3".equals(info.getStarLevel()) || "4".equals(info.getStarLevel()) || "5".equals(info.getStarLevel()))) {
                        //3-5星的数据
                        count += 1;
                    }
                }
                sevenDaysOther.add(count);

            }

        } catch (Exception e) {
            log.error("getPanelCount获取数据失败", e);
        }

        resMap.put("isEmp", roleMap.get("is_emp"));
        resMap.put("sevenDays", sevenDays);
        resMap.put("sevenDaysTotal", sevenDaysTotal);
        resMap.put("sevenDaysOther", sevenDaysOther);
        return AjaxResult.success(resMap);
    }

    /**
     * 获取首页的客户数量
     * 员工统计所有状态的数据
     * 部门统计所有人员的客户数量
     *
     * @return
     */
    @GetMapping("/getCustCount")
    public AjaxResult getCustCount() {
        List<String> xAxis = new ArrayList<>();
        List<Integer> yAxis = new ArrayList<>();


        Map<String, Object> resMap = null;
        Map<String, Object> roleMap = null;


        try {
            resMap = new HashMap<String, Object>();
            CustInfo custInfo = new CustInfo();
            // 当前用户
            SysUser user = getLoginUser().getUser();
            //获取登录账号的角色信息
            roleMap = userInfoComm.getUserRoleCode();
            if (roleMap.get("is_emp").equals("1")) {
                //如果是业务员只查询自己的数据
                //根据状态分组，计算总数量
                Map<String, Object> inParams = new HashMap<>();
                inParams.put("userId", user.getUserId());
                List<Map<String, Object>> aCollectionOfStatisticalResults = indexDashboardService.groupByCustStatus(inParams);
                for (Map<String, Object> aCollectionOfStatisticalResult : aCollectionOfStatisticalResults) {
                    xAxis.add(MapUtils.getString(aCollectionOfStatisticalResult, "status"));
                    String num = MapUtils.getString(aCollectionOfStatisticalResult, "num", "0");
                    yAxis.add(Integer.valueOf(num));
                }

            } else {
                SysUser sysUser = new SysUser();
                sysUser.setDeptId(user.getDeptId());
                //部门则是计算所有人员的数据
                List<SysUser> sysUsers = iSysUserService.selectUserList(sysUser);
                for (SysUser sysUser1 : sysUsers) {

                    CustInfo custInfo1 = new CustInfo();
                    custInfo1.setUserId(sysUser1.getUserId());
                    int num = custInfoService.selectCustInfoList(custInfo1).size();
                    if (num != 0) {
                        xAxis.add(sysUser1.getNickName());
                        yAxis.add(num);
                    }
                }
            }


        } catch (Exception e) {
            log.error("getCustCount获取数据失败", e);
        }

        resMap.put("isEmp", roleMap.get("is_emp"));
        resMap.put("xAxis", xAxis);
        resMap.put("yAxis", yAxis);
        return AjaxResult.success(resMap);
    }


    /**
     * 获取最近七天的日期
     *
     * @return
     */
    public List<String> getSevenDays() {
        List<String> dates = new ArrayList<String>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -6);
        for (int i = 0; i < 7; i++) {
            Date date = calendar.getTime();
            String formattedDate = dateFormat.format(date);
            dates.add(formattedDate);
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        return dates;
    }
}
